package com.thesis.manage.config;

import com.thesis.manage.common.utils.Result;
import com.thesis.manage.feign.UserService;
import com.thesis.manage.service.model.StateCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author php
 * @date 2018/2/2
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        Result result = this.userService.checkToken(token);
        if (result.getStatus() != StateCodeEnum.SUCCESS.getValue().intValue()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        this.userService.expire(token, 60 * 60 * 30);
        return super.preHandle(request, response, handler);
    }
}
